package datastructure.trie;

class Trie {

    // 26 叉 树  以及本节点是否是根节点
    Trie[] child = new Trie[26];
    boolean isLeaf = false;

    /** Initialize your data structure here. */
    public Trie() {

    }

    /** Inserts a word into the datastructure.trie. */
    public void insert(String word) {
        Trie node = this;
        for(int i = 0; i < word.length(); i++) {
            char wordI = word.charAt(i);
            int childIndex = wordI - 'a';
            if(node.child[childIndex] == null) {
                node.child[childIndex] = new Trie();
            }
            node = node.child[childIndex];
        }
        // 代表到这个节点  有一个单词结束了   但是可能还有下文
        node.isLeaf = true;
    }

    /** Returns if the word is in the datastructure.trie. */
    public boolean search(String word) {
        Trie node = this;
        for(int i = 0; i < word.length(); i++) {
            char wordI = word.charAt(i);
            int childIndex = wordI - 'a';
            if(node.child[childIndex] != null) {
                node = node.child[childIndex];
            } else {
                return false;
            }
        }
        return node.isLeaf;
    }

    /** Returns if there is any word in the datastructure.trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie node = this;
        for(int i = 0; i < prefix.length(); i++) {
            char wordI = prefix.charAt(i);
            int childIndex = wordI - 'a';
            if(node.child[childIndex] != null) {
                node = node.child[childIndex];
            } else {
                return false;
            }
        }
        return true;
    }
}
